#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简化版系统信息查看器
只使用Python标准库，无需安装第三方依赖
作者: AI Assistant
功能: 收集并展示Windows系统信息，生成详细报告
"""

import os
import sys
import platform
import socket
import datetime
import time
import subprocess
import json
from pathlib import Path
import shutil

class SimpleSystemInfoViewer:
    def __init__(self):
        self.info_data = {}
        
    def print_header(self):
        """打印程序标题"""
        print("=" * 60)
        print("           🖥️  Windows 系统信息查看器  🖥️")
        print("           (简化版 - 仅使用标准库)")
        print("=" * 60)
        print()
        
    def print_progress(self, message, step, total_steps):
        """显示进度信息"""
        progress = int((step / total_steps) * 50)
        bar = "█" * progress + "░" * (50 - progress)
        percentage = int((step / total_steps) * 100)
        print(f"\r[{bar}] {percentage}% - {message}", end="", flush=True)
        if step == total_steps:
            print()  # 完成后换行
            
    def get_basic_system_info(self):
        """获取基本系统信息"""
        try:
            uname = platform.uname()
            
            self.info_data['basic_info'] = {
                '计算机名称': platform.node(),
                '操作系统': f"{uname.system} {uname.release}",
                '系统版本': uname.version,
                '系统架构': uname.machine,
                '处理器': uname.processor,
                'Python版本': platform.python_version(),
                '当前用户': os.getlogin() if hasattr(os, 'getlogin') else os.environ.get('USERNAME', '未知'),
                '当前工作目录': os.getcwd(),
            }
        except Exception as e:
            print(f"获取基本系统信息时出错: {e}")
            
    def get_disk_info(self):
        """获取磁盘信息"""
        try:
            disk_info = []
            
            # 获取所有驱动器
            drives = ['%s:' % d for d in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' if os.path.exists('%s:' % d)]
            
            for drive in drives:
                try:
                    total, used, free = shutil.disk_usage(drive)
                    disk_info.append({
                        '驱动器': drive,
                        '总大小': f"{total / (1024**3):.2f} GB",
                        '已用空间': f"{used / (1024**3):.2f} GB",
                        '可用空间': f"{free / (1024**3):.2f} GB",
                        '使用率': f"{(used / total) * 100:.1f}%"
                    })
                except (PermissionError, OSError):
                    continue
                    
            self.info_data['disk_info'] = disk_info
        except Exception as e:
            print(f"获取磁盘信息时出错: {e}")
            
    def get_network_info(self):
        """获取网络信息"""
        try:
            network_info = {}
            
            # 获取主机名和IP
            hostname = socket.gethostname()
            try:
                local_ip = socket.gethostbyname(hostname)
            except:
                local_ip = "无法获取"
                
            network_info['主机信息'] = {
                '主机名': hostname,
                '本地IP': local_ip,
            }
            
            # 尝试获取更多网络信息
            try:
                # 获取默认网关（通过route命令）
                result = subprocess.run(['route', 'print', '0.0.0.0'], 
                                      capture_output=True, text=True, timeout=5)
                if result.returncode == 0:
                    lines = result.stdout.split('\n')
                    for line in lines:
                        if '0.0.0.0' in line and 'Gateway' not in line:
                            parts = line.split()
                            if len(parts) >= 3:
                                network_info['默认网关'] = parts[2]
                                break
            except:
                network_info['默认网关'] = "无法获取"
                
            self.info_data['network_info'] = network_info
        except Exception as e:
            print(f"获取网络信息时出错: {e}")
            
    def get_environment_info(self):
        """获取环境变量信息"""
        try:
            important_vars = ['PATH', 'TEMP', 'TMP', 'USERNAME', 'USERPROFILE', 'COMPUTERNAME']
            env_info = {}
            
            for var in important_vars:
                env_info[var] = os.environ.get(var, '未设置')
                
            self.info_data['environment_info'] = env_info
        except Exception as e:
            print(f"获取环境信息时出错: {e}")
            
    def get_system_time_info(self):
        """获取系统时间信息"""
        try:
            now = datetime.datetime.now()
            
            time_info = {
                '当前时间': now.strftime('%Y-%m-%d %H:%M:%S'),
                '时区': str(now.astimezone().tzinfo),
                '星期': now.strftime('%A'),
                '年份第几天': now.timetuple().tm_yday,
            }
            
            self.info_data['time_info'] = time_info
        except Exception as e:
            print(f"获取时间信息时出错: {e}")
            
    def get_python_info(self):
        """获取Python环境信息"""
        try:
            python_info = {
                'Python版本': platform.python_version(),
                'Python实现': platform.python_implementation(),
                'Python编译器': platform.python_compiler(),
                'Python路径': sys.executable,
                '模块搜索路径': sys.path[:3],  # 只显示前3个路径
            }
            
            self.info_data['python_info'] = python_info
        except Exception as e:
            print(f"获取Python信息时出错: {e}")
            
    def display_info(self):
        """在控制台显示信息"""
        print("\n" + "="*60)
        print("📊 系统信息概览")
        print("="*60)
        
        # 显示基本信息
        if 'basic_info' in self.info_data:
            print("\n🖥️ 基本系统信息:")
            for key, value in self.info_data['basic_info'].items():
                print(f"  {key}: {value}")
                
        # 显示磁盘信息
        if 'disk_info' in self.info_data:
            print("\n💿 磁盘信息:")
            for i, disk in enumerate(self.info_data['disk_info']):
                print(f"  驱动器 {i+1}:")
                for key, value in disk.items():
                    print(f"    {key}: {value}")
                    
        # 显示网络信息
        if 'network_info' in self.info_data:
            print("\n🌐 网络信息:")
            for category, info in self.info_data['network_info'].items():
                if isinstance(info, dict):
                    print(f"  {category}:")
                    for key, value in info.items():
                        print(f"    {key}: {value}")
                else:
                    print(f"  {category}: {info}")
                    
        # 显示时间信息
        if 'time_info' in self.info_data:
            print("\n⏰ 时间信息:")
            for key, value in self.info_data['time_info'].items():
                print(f"  {key}: {value}")
                
        # 显示Python信息
        if 'python_info' in self.info_data:
            print("\n🐍 Python环境信息:")
            for key, value in self.info_data['python_info'].items():
                if isinstance(value, list):
                    print(f"  {key}:")
                    for item in value:
                        print(f"    - {item}")
                else:
                    print(f"  {key}: {value}")
                    
        # 显示环境变量
        if 'environment_info' in self.info_data:
            print("\n🔧 重要环境变量:")
            for key, value in self.info_data['environment_info'].items():
                # 截断过长的PATH变量
                if key == 'PATH' and len(str(value)) > 100:
                    value = str(value)[:100] + "..."
                print(f"  {key}: {value}")
                
    def save_to_file(self):
        """保存信息到文件"""
        try:
            timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"系统信息报告_{timestamp}.txt"
            
            with open(filename, 'w', encoding='utf-8') as f:
                f.write("=" * 80 + "\n")
                f.write("                    Windows 系统信息详细报告\n")
                f.write("                      (简化版 - 标准库)\n")
                f.write("=" * 80 + "\n")
                f.write(f"生成时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write("=" * 80 + "\n\n")
                
                # 写入基本信息
                if 'basic_info' in self.info_data:
                    f.write("🖥️ 基本系统信息\n")
                    f.write("-" * 40 + "\n")
                    for key, value in self.info_data['basic_info'].items():
                        f.write(f"{key:<20}: {value}\n")
                    f.write("\n")
                    
                # 写入磁盘信息
                if 'disk_info' in self.info_data:
                    f.write("💿 磁盘信息\n")
                    f.write("-" * 40 + "\n")
                    for i, disk in enumerate(self.info_data['disk_info']):
                        f.write(f"驱动器 {i+1}:\n")
                        for key, value in disk.items():
                            f.write(f"  {key:<18}: {value}\n")
                        f.write("\n")
                        
                # 写入网络信息
                if 'network_info' in self.info_data:
                    f.write("🌐 网络信息\n")
                    f.write("-" * 40 + "\n")
                    for category, info in self.info_data['network_info'].items():
                        if isinstance(info, dict):
                            f.write(f"{category}:\n")
                            for key, value in info.items():
                                f.write(f"  {key:<18}: {value}\n")
                        else:
                            f.write(f"{category}: {info}\n")
                    f.write("\n")
                        
                # 写入时间信息
                if 'time_info' in self.info_data:
                    f.write("⏰ 时间信息\n")
                    f.write("-" * 40 + "\n")
                    for key, value in self.info_data['time_info'].items():
                        f.write(f"{key:<20}: {value}\n")
                    f.write("\n")
                    
                # 写入Python信息
                if 'python_info' in self.info_data:
                    f.write("🐍 Python环境信息\n")
                    f.write("-" * 40 + "\n")
                    for key, value in self.info_data['python_info'].items():
                        if isinstance(value, list):
                            f.write(f"{key}:\n")
                            for item in value:
                                f.write(f"  - {item}\n")
                        else:
                            f.write(f"{key:<20}: {value}\n")
                    f.write("\n")
                    
                # 写入环境变量
                if 'environment_info' in self.info_data:
                    f.write("🔧 重要环境变量\n")
                    f.write("-" * 40 + "\n")
                    for key, value in self.info_data['environment_info'].items():
                        f.write(f"{key}:\n")
                        if key == 'PATH':
                            # PATH变量按分号分割显示
                            paths = str(value).split(';')
                            for path in paths[:10]:  # 只显示前10个路径
                                f.write(f"  {path}\n")
                            if len(paths) > 10:
                                f.write(f"  ... 还有 {len(paths) - 10} 个路径\n")
                        else:
                            f.write(f"  {value}\n")
                        f.write("\n")
                        
                f.write("=" * 80 + "\n")
                f.write("报告生成完成！\n")
                f.write("\n注意：这是简化版报告，使用Python标准库生成。\n")
                f.write("如需更详细的硬件信息，请安装第三方库后运行完整版。\n")
                
            print(f"\n✅ 系统信息已保存到文件: {filename}")
            return filename
            
        except Exception as e:
            print(f"保存文件时出错: {e}")
            return None
            
    def run(self):
        """运行主程序"""
        self.print_header()
        
        tasks = [
            ("正在获取基本系统信息...", self.get_basic_system_info),
            ("正在获取磁盘信息...", self.get_disk_info),
            ("正在获取网络信息...", self.get_network_info),
            ("正在获取时间信息...", self.get_system_time_info),
            ("正在获取Python环境信息...", self.get_python_info),
            ("正在获取环境变量信息...", self.get_environment_info),
        ]
        
        total_tasks = len(tasks)
        
        for i, (message, task_func) in enumerate(tasks, 1):
            self.print_progress(message, i-1, total_tasks)
            time.sleep(0.3)  # 模拟处理时间
            task_func()
            self.print_progress(message, i, total_tasks)
            
        print("\n")
        
        # 显示信息
        self.display_info()
        
        # 保存到文件
        print("\n正在生成报告文件...")
        filename = self.save_to_file()
        
        if filename:
            print(f"\n🎉 任务完成！系统信息已收集并保存到: {filename}")
            print("\n📝 报告包含以下信息:")
            print("  • 基本系统信息（操作系统、处理器等）")
            print("  • 磁盘使用情况")
            print("  • 网络配置信息")
            print("  • 系统时间信息")
            print("  • Python环境信息")
            print("  • 重要环境变量")
        else:
            print("\n❌ 保存文件失败，但控制台信息显示正常。")

def main():
    """主函数"""
    try:
        print("正在启动系统信息查看器...")
        viewer = SimpleSystemInfoViewer()
        viewer.run()
    except KeyboardInterrupt:
        print("\n\n程序被用户中断。")
    except Exception as e:
        print(f"\n程序运行出错: {e}")
        import traceback
        traceback.print_exc()
    finally:
        input("\n按回车键退出...")

if __name__ == "__main__":
    main()